package com.example.smartcity.ui.person.login

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MenuItem
import com.example.smartcity.R
import com.example.smartcity.databinding.ActivityLoginPwdBinding
import com.example.smartcity.logic.net_work.Response.getLoginPwd
import com.example.smartcity.logic.utils.Toast.Companion.showToast
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody
import org.json.JSONObject


/**
 * 修改密码
 */
class LoginPwdActivity : AppCompatActivity() {
    private lateinit var mBinding: ActivityLoginPwdBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivityLoginPwdBinding.inflate(layoutInflater)
        setContentView(mBinding.root)
        title = "修改密码"
        supportActionBar?.setDisplayHomeAsUpEnabled(true)


        // 修改密码
        setPwd()
    }

    /**
     * 修改密码
     */
    @OptIn(DelicateCoroutinesApi::class)
    private fun setPwd() {
        mBinding.userOk.setOnClickListener {
            if (mBinding.userPwd.text.isEmpty() || mBinding.userNewPwd1.text.isEmpty() || mBinding.userNewPwd2.text.isEmpty()){
                runOnUiThread {
                    "原密码和新密码不能为空".showToast()
                }
            }else {
                if (mBinding.userNewPwd1.text.toString() == mBinding.userNewPwd2.text.toString() ){
                    // 获取token
                    getSharedPreferences("token", MODE_PRIVATE).apply {
                        val token = getString("token", "")
                        GlobalScope.launch {
                            getLoginPwd(
                                token.toString(),
                                RequestBody.create(
                                    "application/json".toMediaType(),
                                    JSONObject().apply {
                                        put("oldPassword", mBinding.userPwd.text)
                                        put("newPassword", mBinding.userNewPwd1.text)
                                    }.toString()
                                )
                            ).apply {
                                runOnUiThread {
                                    this@LoginPwdActivity.finish()
                                    if (this.code == "200") "修改密码成功!".showToast()
                                }
                            }
                        }
                    }
                }else {
                    runOnUiThread {
                        "新密码不一致?".showToast()
                    }
                }

            }

        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // 销毁意图
        this.finish()
        return super.onOptionsItemSelected(item)
    }
}